from django import forms
from django.shortcuts import render, redirect
from django.urls import reverse

from utils.bootstrap import BootstrapForm
from web.models import Level


class LevelModelForm(BootstrapForm, forms.ModelForm):
    class Meta:
        model = Level
        fields = ['title', 'percent']


def level_list(request):
    queryset = Level.objects.filter(active=True)
    return render(request, 'level_list.html', {'queryset': queryset})


def level_add(request):
    if request.method == 'GET':
        form = LevelModelForm()
        return render(request, 'form.html', {'form': form})
    form = LevelModelForm(request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    form.save()
    return redirect(reverse('level_list'))


def level_edit(request, pk):
    level_obj = Level.objects.filter(id=pk, active=True).first()

    if request.method == 'GET':
        form = LevelModelForm(instance=level_obj)
        return render(request, 'form.html', {'form': form})

    form = LevelModelForm(request.POST, instance=level_obj)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    form.save()
    return redirect(reverse('level_list'))


def level_delete(request, pk):
    Level.objects.filter(id=pk).update(active=False)
    return redirect(reverse('level_list'))
